import { _decorator, Mesh, MeshRenderer } from 'cc';
import { BasicComponet } from '../../../../Init/Basic/BasicComponet';
import { MergeItem, MergetMesh } from './MergetMesh';
const { ccclass } = _decorator;

/**同种模型合并 -通用 适合做  位移-缩放-旋转-动画 
 * 用于继承
*/
@ccclass('MergeMeshEffect')
export class MergeMeshEffect extends BasicComponet {
    protected msRenderer: MeshRenderer = null;
    //需要合并的mesh
    protected mergeMesh: Mesh = null;

    protected _mergeRecs: MergetMesh[] = [];

    // #region -----------流程------------
    public initSub() {

    }
    public onEvents() {

    }
    public setData(d: { meshRenderer: MeshRenderer, mergeMesh: Mesh }) {
        this.msRenderer = d.meshRenderer;
        this.mergeMesh = d.mergeMesh;
    }
    public reset() {
        for (let i = 0; i < this._mergeRecs.length; i++) {
            const rec = this._mergeRecs[i];
            rec.reset();
        }
    }
    public customUpdate(dt) {
        for (let i = 0; i < this._mergeRecs.length; i++) {
            const rec = this._mergeRecs[i];
            rec.customUpdate(dt);
        }
    }
    public customLateUpdate(dt) {

    }

    // #endregion

    // #region ---私有--
    /**创建新的合并对象 */
    protected createMergeMesh() {
        let e = new MergetMesh(this.onAnimFinished.bind(this));
        e.setData({ mesh: this.mergeMesh, meshRenderer: this.msRenderer });
        this._mergeRecs.push(e);
        return e;
    }

    protected onAnimFinished() {

    }

    // #endregion

    // #region ----------对外-------
    /**返回指定数量的 item count 需要小于 110 */
    public getMergeItemArr(out: MergeItem[], count: number) {
        if (count > 110) {
            count = 110;
        }

        if (this._mergeRecs.length == 0) {
            this.createMergeMesh();
        }

        let n = 0;
        for (let i = 0; i < this._mergeRecs.length; i++) {
            const e = this._mergeRecs[i];
            if (n >= count) break;
            e.getMergeItems(out, count - n);
            n = out.length;
        }

        if (n < count) {
            let cmp = this.createMergeMesh();
            cmp.getMergeItems(out, count - n);
        }
    }
    // #endregion

}

